package org.fxcontainer.validation.validator
{

	import mx.validators.ValidationResult;
	import org.fxcontainer.validation.validator.base.BaseValidator;
	import org.fxcontainer.validation.validator.utils.ValidationErrorCodes;

	/**
	 * The combobox component validator.
	 * @author Izzet_Mustafayev
	 */
	public class ComboBoxValidator extends BaseValidator
	{
		public function ComboBoxValidator()
		{
			super();
		}

		/**
		 * Holds object field name to validate.
		 * @default null
		 */
		private var _requiredObjectFieldName:String;

		/**
		 * Combobox selection item state. Indicates whether combobox item was selected.
		 * @default false
		 */
		private var _selected:Boolean;

		/**
		 * Set emptyCollectionErrorKey
		 */
		public function set emptyCollectionErrorKey(value:String):void
		{
			setErrorMessageKey(ValidationErrorCodes.EMPTY_COLLECTION_ERROR, value);
		}

		/**
		 * Set notCheckedCollectionError
		 */
		public function set notSelectedCollectionErrorKey(value:String):void
		{
			setErrorMessageKey(ValidationErrorCodes.NOT_SELECTED_COLLECTION_ERROR, value);
		}

		/**
		 * Set required object field name to validate.
		 * @param value the value to set
		 */
		public function set requiredObjectFieldName(value:String):void
		{
			_requiredObjectFieldName=value;
		}

		[Inspectable(category="General",defaultValue="true")]
		/**
		 * If <code>true</code>, specifies that a collection must have one or more checked items
		 *
		 * @default false
		 */
		public function get selected():Boolean
		{
			return _selected;
		}

		/**
		 * @private
		 */
		public function set selected(value:Boolean):void
		{
			_selected=value;
		}

		/**
		 * Overridded validation processing base method.
		 * @param value the object value to validate
		 * @return validation results
		 */
		override protected function doValidation(value:Object):Array
		{
			var results:Array=[];
			if (!_selected)
			{
				var isSelected:Boolean=false;
				//check whether required object field was set
				if (null != _requiredObjectFieldName && value.hasOwnProperty(_requiredObjectFieldName))
				{
					if (null != value[_requiredObjectFieldName])
					{
						var objectValue:*=value[_requiredObjectFieldName];
						if (objectValue is Number && objectValue > 0)
						{
							isSelected=true;
						}
						if (objectValue is String && null != objectValue)
						{
							isSelected=true;
						}
					}
				}
				if (!isSelected)
				{
					results.push(new ValidationResult(true, property, ValidationErrorCodes.NOT_SELECTED_COLLECTION_ERROR, getErrorMessage(ValidationErrorCodes.NOT_SELECTED_COLLECTION_ERROR)));
				}
				_selected=isSelected;
			}


			return results;
		}

	}
}